package br.com.timecardforpeon.dialog;

import java.util.Date;

import android.app.Dialog;
import android.content.Context;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import br.com.timecardforpeon.R;
import br.com.timecardforpeon.domain.Day;
import br.com.timecardforpeon.exception.TimeCardException;
import br.com.timecardforpeon.sqlite.domain.DayDao;
import br.com.timecardforpeon.util.Util;

public class NotesDialog extends Dialog {

	private final DayDao dayDao;
	private final Date actualDate;
	
	public NotesDialog(Date actualDate, Context context) {
		super(context);
		this.actualDate = actualDate;
		this.dayDao = new DayDao(this.getContext());
		
		this.setContentView(R.layout.notes_dialog);
		this.setTitle(R.string.notes);
		
		this.initializeData();
		this.initializeListeners();
	}

	private void initializeData() {
		Day day = this.dayDao.getByDay(this.actualDate);
		Util.<EditText>setViewText(this, R.id.notesEditText, day.getNotes());
	}

	private void initializeListeners() {
		Button saveButton = Util.<Button>getViewById(this, R.id.saveNotesButton);
		saveButton.setOnClickListener(new SaveClickListener(this));

		Button cancelButton = Util.<Button>getViewById(this, R.id.cancelNotesButton);
		cancelButton.setOnClickListener(new CancelClickListener(this));
	}
	
	class SaveClickListener implements android.view.View.OnClickListener {

		private Dialog dialog;
		
		public SaveClickListener(Dialog dialog) {
			this.dialog = dialog;
		}

		@Override
		public void onClick(View v) {
			
			Day day = dayDao.getByDay(actualDate);
			day.setNotes(Util.<EditText>getEditText(this.dialog, R.id.notesEditText));
			
			try {
				
				dayDao.update(day);
				
			} catch (TimeCardException e) {
				Toast.makeText(this.dialog.getContext(), e.getMessage(), Toast.LENGTH_LONG).show();
			}
			Toast.makeText(this.dialog.getContext(), R.string.notesUpdated, Toast.LENGTH_LONG).show();
			
			this.dialog.dismiss();
		}
	}
	
	class CancelClickListener implements android.view.View.OnClickListener {
		
		private Dialog dialog;
		
		public CancelClickListener(Dialog dialog) {
			this.dialog = dialog;
		}

		@Override
		public void onClick(View view) {
			this.dialog.dismiss();
		}
	}
}